package cc.xsubj.trading.inventory;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.zip.GZIPInputStream;

public class ItemRegistry {
	private static List<ItemType> items;
	private static Map<String, ItemType> nameToItem;
	
	static {
		populateItems();
		populateNameMap();
	}
	
	private static void populateItems()
	{
	    items = new ArrayList<ItemType>();
	    
	    try
        {
            Scanner sc = new Scanner(new GZIPInputStream(new BufferedInputStream(new FileInputStream("data/items.dat"))));
            sc.useDelimiter("[|\n]+");
            while(sc.hasNextLine())
            {
                String name = sc.next();
                int value = sc.nextInt();
                double weight = sc.nextDouble();
                System.out.println("Adding ItemType("+name+", "+value+", "+weight+")");
                items.add(new ItemType(name, value, weight));
            }
        } catch (FileNotFoundException e)
        {
            items.add(new ItemType("AppleToot", 1, 0.5));
            items.add(new ItemType("Gold Coin", 100, 1));
            e.printStackTrace();
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
	}
	
	private static void populateNameMap()
	{
		nameToItem = new HashMap<String, ItemType>();
		for (ItemType item : items)
		{
			nameToItem.put(item.name, item);
		}
	}
	
	public static int getNumberOfItems()
	{
		return items.size();
	}
	
	public static ItemType getItemByName(String name)
	{
		return nameToItem.get(name);
	}
	
	public static ItemType getItemByID(int id)
	{
		return items.get(id);
	}
	
	public static int getIDByItem(ItemType record){
		for (int i = 0; i < items.size(); i++)
		{
			if (items.get(i) == record)
				return i;
		}
		return -1;
	}
}
